package com.jdplat.jdm.web.controller.system;

import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jdplat.jdm.core.web.controller.BaseController;
import com.jdplat.jdm.core.web.utils.MD5;
import com.jdplat.jdm.core.web.utils.StrKit;
import com.jdplat.jdm.web.service.system.ISystemLoginService;

/**
 * Created by qirp on 2016/11/16.
 */
@Controller
@RequestMapping("/sys")
public class SystemLoginController extends BaseController {
	
	protected Logger logger = LoggerFactory.getLogger(SystemLoginController.class);
	
	@Autowired
	public ISystemLoginService systemLoginService;

    @RequestMapping(value = "/login" ,method = {RequestMethod.POST})
    public String login(RedirectAttributes flash){
    	Map<String, Object> requestData = getRequestList(request);
    	String userName = requestData.get("name").toString();
    	String passWord = requestData.get("pwd").toString();
    	if(StrKit.isEmpty(userName) && StrKit.isEmpty(passWord)){
    		flash.addAttribute("msg", "用户名或者密码不能为空！");
    	}else{
    		UsernamePasswordToken token = new UsernamePasswordToken(userName,MD5.encodeString(passWord));
    		token.setRememberMe(true);
    		Subject currentUser = SecurityUtils.getSubject();
    		currentUser.login(token);
    	}
    	return "redirect:/system/login";
    }
	
	/**
	 * 用户登出
	 */
	@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.GET })
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "system/login";
	}
	
	/**
	 * 登录失败
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String fail(ModelMap model)  {
		return "system/login";
	}
}
